<template>
    <view class="container">
        <view class="header">
            <text class="pet-name">{{ pet.name || '未命名' }}</text>
            <view class="level-info">
                <text class="level">Lv.{{ pet.level }}</text>
                <view class="exp-bar">
                    <view class="exp-progress" :style="{ width: expPercentage + '%' }"></view>
                </view>
                <text class="exp-text">{{ pet.exp }}/{{ pet.expToNextLevel }}</text>
            </view>
        </view>

        <view class="pet-status">
            <view class="status-panel">
                <view class="status-item">
                    <text class="status-icon">🍖</text>
                    <view class="progress-bar">
                        <view class="progress" :style="{ width: pet.hunger + '%' }"></view>
                    </view>
                </view>
                <view class="status-item">
                    <text class="status-icon">💖</text>
                    <view class="progress-bar">
                        <view class="progress happiness" :style="{ width: pet.happiness + '%' }"></view>
                    </view>
                </view>
                <view class="status-item">
                    <text class="status-icon">⚡</text>
                    <view class="progress-bar">
                        <view class="progress energy" :style="{ width: pet.energy + '%' }"></view>
                    </view>
                </view>
            </view>
        </view>
        <view class="pet-container" :class="petMood">
            <image class="pet-image" :src="getPetMoodImage()" mode="aspectFit" @tap="petTap"></image>
            
            <!-- 心情指示器 -->
            <view class="mood-indicator" :class="petMood">
                <view class="mood-icon">
                    <text v-if="petMood === 'happy'">😊</text>
                    <text v-else-if="petMood === 'normal'">😐</text>
                    <text v-else>😢</text>
                </view>
                <view class="mood-text">{{ getMoodText }}</view>
            </view>

            <view class="interaction-effects">
                <view class="effect" v-for="(effect, index) in effects" :key="index"
                    :class="effect.type"
                    :style="{ top: effect.top + '%' }">
                    {{ effect.value }}
                </view>
            </view>
        </view>
        
        <view class="action-buttons">
            <button class="action-btn" 
                @tap="handleFeed" 
                :disabled="!canFeed"
                :class="{ disabled: !canFeed }">
                <image src="/static/icons/food.svg" mode="aspectFit"></image>
                <text>喂食</text>
            </button>
            <button class="action-btn" 
                @tap="handlePlay" 
                :disabled="!canPlay"
                :class="{ disabled: !canPlay }">
                <image src="/static/icons/play.svg" mode="aspectFit"></image>
                <text>玩耍</text>
            </button>
            <button class="action-btn" 
                @tap="handleSleep" 
                :disabled="!canSleep"
                :class="{ disabled: !canSleep }">
                <image src="/static/icons/sleep.svg" mode="aspectFit"></image>
                <text>休息</text>
            </button>
        </view>

        <view class="background-animation">
            <view class="bubble" v-for="i in 10" :key="i"></view>
        </view>
    </view>
</template>

<script>
import { mapState, mapActions } from 'vuex'

export default {
    data() {
        return {
            interactionCooldown: false,
            lastUpdateTime: Date.now(),
            effects: [],
            effectId: 0,
            autoSaveInterval: null
        }
    },
    onLoad() {
        // 初始化游戏
        this.$store.dispatch('initGame')
        // 启动自动保存
        this.$store.dispatch('startAutoSave')
    },
    onUnload() {
        // 保存游戏状态
        this.$store.dispatch('saveGame')
    },
    computed: {
        ...mapState(['pet']),
        petMood() {
            const { happiness } = this.pet
            if (happiness >= 80) return 'happy'
            if (happiness >= 50) return 'normal'
            return 'sad'
        },
        getMoodText() {
            const { happiness } = this.pet
            if (happiness >= 80) return '心情愉悦'
            if (happiness >= 50) return '心情一般'
            return '心情低落'
        },
        canFeed() {
            return !this.interactionCooldown && this.pet.hunger < 100
        },
        canPlay() {
            return !this.interactionCooldown && this.pet.energy > 0
        },
        canSleep() {
            return !this.interactionCooldown && this.pet.energy < 100
        },
        canPetTap() {
            return !this.interactionCooldown && this.pet.happiness < 100
        },
        expPercentage() {
            return (this.pet.exp / this.pet.expToNextLevel) * 100
        },
        formatPlayTime() {
            const minutes = this.pet.stats.playTime
            if (minutes < 60) {
                return minutes + '分钟'
            } else {
                const hours = Math.floor(minutes / 60)
                const remainingMinutes = minutes % 60
                return `${hours}小时${remainingMinutes}分钟`
            }
        }
    },
    methods: {
        ...mapActions(['feedPet', 'playWithPet', 'sleep', 'saveGame']),
        updateStatus(key, value) {
            this.$store.commit('updatePetStatus', { key, value })
        },
        getPetMoodImage() {
            return `/static/pet/${this.petMood}.svg`
        },
        addEffect(type, value) {
            const id = this.effectId++
            const effect = {
                id,
                type,
                value: value > 0 ? `+${value}` : value,
                top: Math.random() * 30 + 35
            }
            this.effects.push(effect)
            setTimeout(() => {
                const index = this.effects.findIndex(e => e.id === id)
                if (index !== -1) {
                    this.effects.splice(index, 1)
                }
            }, 1000)
        },
        async handleFeed() {
            if (!this.canFeed) return
            
            this.interactionCooldown = true
            try {
                const result = await this.feedPet('BASIC')
                if (result) {
                    this.addEffect('hunger', 30)
                    this.addEffect('happiness', 10)
                }
            } catch (error) {
                console.error('Feed error:', error)
            }
            
            setTimeout(() => {
                this.interactionCooldown = false
            }, 500)
        },
        async handlePlay() {
            if (!this.canPlay) return
            
            this.interactionCooldown = true
            try {
                const result = await this.playWithPet('BASIC')
                if (result) {
                    this.addEffect('happiness', 30)
                    this.addEffect('energy', -15)
                }
            } catch (error) {
                console.error('Play error:', error)
            }
            
            setTimeout(() => {
                this.interactionCooldown = false
            }, 500)
        },
        async handleSleep() {
            if (!this.canSleep) return
            
            this.interactionCooldown = true
            try {
                const result = await this.sleep()
                if (result) {
                    const energyGain = 100 - this.pet.energy
                    this.addEffect('energy', energyGain)
                }
            } catch (error) {
                console.error('Sleep error:', error)
            }
            
            setTimeout(() => {
                this.interactionCooldown = false
            }, 500)
        },
        petTap() {
            if (!this.canPetTap) return
            
            this.interactionCooldown = true
            const happinessBoost = Math.floor(Math.random() * 5) + 1
            const newHappiness = Math.min(this.pet.happiness + happinessBoost, 100)
            
            this.updateStatus('happiness', newHappiness)
            this.addEffect('happiness', happinessBoost)
            
            setTimeout(() => {
                this.interactionCooldown = false
            }, 300)
        },
        updatePetStatus() {
            const now = Date.now()
            const minutesElapsed = (now - this.lastUpdateTime) / 60000
            
            if (minutesElapsed >= 1) {
                // 更新饥饿度
                const newHunger = Math.max(this.pet.hunger - (1.2 * minutesElapsed), 0)
                this.updateStatus('hunger', newHunger)
                
                // 更新心情
                const newHappiness = Math.max(this.pet.happiness - (0.8 * minutesElapsed), 0)
                this.updateStatus('happiness', newHappiness)
                
                // 更新体力
                if (this.pet.energy < 100) {
                    const newEnergy = Math.min(this.pet.energy + (0.8 * minutesElapsed), 100)
                    this.updateStatus('energy', newEnergy)
                }
                
                this.lastUpdateTime = now
            }
        },
        getAchievementIcon(id) {
            const icons = {
                firstPet: '🆕',
                dailyCare: '📅',
                masterTrainer: '⭐',
                gourmet: '🍖'
            }
            return icons[id] || '🎯'
        }
    },
    onShow() {
        this.lastUpdateTime = Date.now()
        this.timer = setInterval(this.updatePetStatus, 60000)
        this.updatePetStatus()
    },
    onHide() {
        if (this.timer) {
            clearInterval(this.timer)
            this.timer = null
        }
        this.lastUpdateTime = Date.now()
    },
    onUnload() {
        if (this.timer) {
            clearInterval(this.timer)
            this.timer = null
        }
    }
}
</script>

<style lang="scss">
@import '@/common/styles/common.scss';

.container {
    min-height: 100vh;
    background: linear-gradient(135deg, #a8edea 0%, #fed6e3 100%);
    position: relative;
    overflow: hidden;
    padding: 20rpx;
}

.header {
    margin-bottom: 20rpx;
    
    .pet-name {
        font-size: 36rpx;
        font-weight: bold;
        color: #333;
        margin-bottom: 10rpx;
    }
    
    .level-info {
        display: flex;
        align-items: center;
        gap: 10rpx;
        
        .level {
            font-size: 28rpx;
            color: #666;
            min-width: 70rpx;
        }
        
        .exp-bar {
            flex: 1;
            height: 16rpx;
            background: #eee;
            border-radius: 8rpx;
            overflow: hidden;
            
            .exp-progress {
                height: 100%;
                background: linear-gradient(90deg, #FFB74D, #FFA726);
                transition: width 0.3s ease;
            }
        }
        
        .exp-text {
            font-size: 24rpx;
            color: #999;
            min-width: 120rpx;
            text-align: right;
        }
    }
}

.pet-status {
    background: rgba(255, 255, 255, 0.7);
    backdrop-filter: blur(20px);
    border-radius: 30rpx;
    padding: 40rpx;
    margin: 20rpx;
    box-shadow: 0 8rpx 32rpx rgba(31, 38, 135, 0.15);
    border: 1px solid rgba(255, 255, 255, 0.18);
    position: relative;
    z-index: 2;

    .status-panel {
        background: rgba(255, 255, 255, 0.9);
        border-radius: 16rpx;
        padding: 20rpx;
        margin-bottom: 20rpx;
        
        .status-item {
            display: flex;
            align-items: center;
            margin-bottom: 15rpx;
            
            &:last-child {
                margin-bottom: 0;
            }
            
            .status-icon {
                font-size: 32rpx;
                margin-right: 15rpx;
                width: 40rpx;
                text-align: center;
            }
            
            .progress-bar {
                flex: 1;
                height: 20rpx;
                background: #eee;
                border-radius: 10rpx;
                overflow: hidden;
                
                .progress {
                    height: 100%;
                    background: linear-gradient(90deg, #4CAF50, #66BB6A);
                    transition: width 0.3s ease;
                    
                    &.happiness {
                        background: linear-gradient(90deg, #F06292, #EC407A);
                    }
                    
                    &.energy {
                        background: linear-gradient(90deg, #64B5F6, #42A5F5);
                    }
                }
            }
        }
    }
}

.pet-info {
    padding: 20rpx;
    
    .info-card {
        background-color: rgba(255, 255, 255, 0.9);
        border-radius: 20rpx;
        padding: 30rpx;
        margin-bottom: 20rpx;
        
        .pet-header {
            display: flex;
            align-items: center;
            margin-bottom: 20rpx;
            
            .pet-avatar {
                width: 120rpx;
                height: 120rpx;
                border-radius: 60rpx;
                background-color: #f0f0f0;
                margin-right: 20rpx;
            }
            
            .pet-level {
                background-color: #ff9966;
                color: white;
                padding: 4rpx 12rpx;
                border-radius: 12rpx;
                font-size: 24rpx;
            }
            
            .pet-name {
                font-size: 32rpx;
                font-weight: bold;
                margin-left: 10rpx;
            }
        }
        
        .exp-bar {
            margin-top: 10rpx;
            background-color: #f0f0f0;
            border-radius: 10rpx;
            height: 20rpx;
            
            .exp-progress {
                background-color: #ff9966;
                height: 100%;
                border-radius: 10rpx;
                transition: width 0.3s;
            }
        }
    }
    
    .stats-grid {
        display: flex;
        justify-content: space-between;
        margin-bottom: 20rpx;
        
        .stat-item {
            flex: 1;
            background-color: rgba(255, 255, 255, 0.9);
            border-radius: 20rpx;
            padding: 20rpx;
            margin: 0 10rpx;
            text-align: center;
            
            &:first-child {
                margin-left: 0;
            }
            
            &:last-child {
                margin-right: 0;
            }
            
            .stat-icon {
                font-size: 48rpx;
                margin-bottom: 10rpx;
            }
            
            .stat-label {
                font-size: 24rpx;
                color: #666;
                margin-bottom: 5rpx;
            }
            
            .stat-value {
                font-size: 28rpx;
                color: #ff9966;
                font-weight: bold;
            }
        }
    }
    
    .achievements-section {
        background-color: rgba(255, 255, 255, 0.9);
        border-radius: 20rpx;
        padding: 20rpx;
        
        .section-title {
            font-size: 28rpx;
            font-weight: bold;
            color: #333;
            margin-bottom: 20rpx;
        }
        
        .achievements-list {
            // 移除固定高度限制
            // height: 400rpx;
            // overflow-y: auto;
        }
    }
}

.pet-container {
    background: rgba(255, 255, 255, 0.7);
    backdrop-filter: blur(20px);
    border-radius: 30rpx;
    padding: 40rpx;
    margin: 20rpx;
    height: 400rpx;
    display: flex;
    justify-content: center;
    align-items: center;
    position: relative;
    box-shadow: 0 8rpx 32rpx rgba(31, 38, 135, 0.15);
    border: 1px solid rgba(255, 255, 255, 0.18);
    z-index: 2;
    transition: all 0.3s ease;
    
    &.happy {
        background: rgba(255, 255, 255, 0.8);
        box-shadow: 0 8rpx 32rpx rgba(50, 205, 50, 0.2);
    }
    
    &.normal {
        background: rgba(255, 255, 255, 0.75);
        box-shadow: 0 8rpx 32rpx rgba(255, 165, 0, 0.2);
    }
    
    &.sad {
        background: rgba(255, 255, 255, 0.7);
        box-shadow: 0 8rpx 32rpx rgba(255, 99, 71, 0.2);
    }

    .pet-image {
        width: 300rpx;
        height: 300rpx;
        transition: transform 0.3s ease;
        filter: drop-shadow(0 4rpx 8rpx rgba(0, 0, 0, 0.2));

        &:active {
            transform: scale(0.95);
        }
    }

    .interaction-effects {
        position: absolute;
        width: 100%;
        height: 100%;
        pointer-events: none;
        
        .effect {
            position: absolute;
            font-size: 24rpx;
            font-weight: bold;
            animation: floatUp 1s ease-out forwards;
            
            &.hunger {
                color: #FFA500;
            }
            
            &.happiness {
                color: #FF69B4;
            }
            
            &.energy {
                color: #32CD32;
            }
        }
    }

    .mood-indicator {
        position: absolute;
        bottom: 20rpx;
        right: 20rpx;
        background: rgba(255, 255, 255, 0.9);
        backdrop-filter: blur(10px);
        border-radius: 30rpx;
        padding: 10rpx 20rpx;
        display: flex;
        align-items: center;
        gap: 10rpx;
        box-shadow: 0 4rpx 8rpx rgba(0, 0, 0, 0.1);
        transition: all 0.3s ease;
        
        .mood-icon {
            font-size: 40rpx;
            line-height: 1;
        }
        
        .mood-text {
            font-size: 24rpx;
            color: #666;
            font-weight: bold;
        }
        
        &.happy {
            background: rgba(255, 255, 255, 0.9);
            border: 1px solid rgba(50, 205, 50, 0.3);
        }
        
        &.normal {
            background: rgba(255, 255, 255, 0.85);
            border: 1px solid rgba(255, 165, 0, 0.3);
        }
        
        &.sad {
            background: rgba(255, 255, 255, 0.8);
            border: 1px solid rgba(255, 99, 71, 0.3);
        }
    }
}

.action-buttons {
    display: flex;
    justify-content: space-around;
    margin: 20rpx;
    position: relative;
    z-index: 2;

    .action-btn {
        background: rgba(255, 255, 255, 0.7);
        backdrop-filter: blur(20px);
        border-radius: 20rpx;
        padding: 20rpx 40rpx;
        display: flex;
        flex-direction: column;
        align-items: center;
        border: 1px solid rgba(255, 255, 255, 0.18);
        box-shadow: 0 4rpx 16rpx rgba(31, 38, 135, 0.1);
        transition: all 0.3s ease;

        &:not(.disabled):active {
            transform: scale(0.95);
            background: rgba(255, 255, 255, 0.8);
        }

        &.disabled {
            opacity: 0.5;
            cursor: not-allowed;
        }

        image {
            width: 60rpx;
            height: 60rpx;
            margin-bottom: 10rpx;
            filter: drop-shadow(0 2rpx 4rpx rgba(0, 0, 0, 0.1));
        }

        text {
            font-size: 24rpx;
            color: #666;
            font-weight: bold;
        }
    }
}

.background-animation {
    position: fixed;
    width: 100%;
    height: 100%;
    top: 0;
    left: 0;
    pointer-events: none;
    z-index: 1;

    .bubble {
        position: absolute;
        border-radius: 50%;
        background: rgba(255, 255, 255, 0.3);
        animation: float 8s infinite;
        
        @for $i from 1 through 10 {
            &:nth-child(#{$i}) {
                $size: random(60) + 20 + px;
                width: $size;
                height: $size;
                left: random(100) * 1%;
                animation-delay: random(8) * -1s;
                animation-duration: (random(4) + 6) * 1s;
            }
        }
    }
}

@keyframes float {
    0% {
        transform: translateY(100vh) scale(0);
        opacity: 0;
    }
    50% {
        opacity: 0.8;
    }
    100% {
        transform: translateY(-100px) scale(1);
        opacity: 0;
    }
}

@keyframes floatUp {
    0% {
        opacity: 0;
        transform: translateY(20rpx);
    }
    20% {
        opacity: 1;
    }
    100% {
        opacity: 0;
        transform: translateY(-40rpx);
    }
}
</style>
